package com.example.reader.ui.main.activity;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.reader.R;
import com.example.reader.R2;
import com.example.reader.ui.base.BaseActivity;
import com.example.reader.ui.main.adapter.HomeFragmentAdapter;
import com.example.reader.ui.main.fragment.BookCityFragment;
import com.example.reader.ui.main.fragment.BookshelfFragment;
import com.example.reader.ui.main.fragment.FindFragment;
import com.example.reader.ui.main.fragment.PickedFragment;
import com.example.reader.widget.DialogSet;
import com.example.reader.widget.mysnackbar.GoodSnackbar;

import java.lang.reflect.Method;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.support.design.widget.TabLayout.MODE_FIXED;


public class MainActivity extends BaseActivity {


    @BindView(R2.id.main_content)
    DrawerLayout main_content;

    @BindView(R2.id.viewpager)
    ViewPager viewpager;

    @BindView(R2.id.tab_layout)
    TabLayout tab_layout;

    @BindView(R2.id.fl_content)
    FrameLayout fl_content;

    private static final String TAG = MainActivity.class.getSimpleName();
    private Toolbar toolbar;
    int statusBarHeight1 = -1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.setDebug(true);
        ButterKnife.bind(this);
        getStatusBarHeight();
        initToolBar();
        initDrawer();
        initViewPager();
        initTabLayout();
    }

    private void initViewPager() {
        HomeFragmentAdapter adapter = new HomeFragmentAdapter(getSupportFragmentManager());
        adapter.addFragment(BookshelfFragment.newInstance());
        adapter.addFragment(PickedFragment.newInstance());
        adapter.addFragment(BookCityFragment.newInstance());
        adapter.addFragment(FindFragment.newInstance());
        viewpager.setAdapter(adapter);
        viewpager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });
        viewpager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                if (position != tab_layout.getSelectedTabPosition()) {
                    tab_layout.getTabAt(position).select();
                }
                // 切换界面 更新toolbar显示
                updateToolbar(position);
            }
        });
    }

    private void updateToolbar(int position) {
        // 只有书架显示menu
        if (position != 0) {
            hideMenu();
            changeToolbarBg();
        } else {
            showMenu();
            resetToolbarBg();
        }
    }

    private void initDrawer() {
        main_content = (DrawerLayout) findViewById(R.id.main_content);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, main_content, toolbar, R.string.app_name, R.string.app_name) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };
    }

    private void getStatusBarHeight() {
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        Log.e("WangJ", "状态栏-方法1:" + statusBarHeight1);
    }

    int[] images = new int[]{R.drawable.maintab_bookstand_icon, R.drawable.maintab_stack_icon
            , R.drawable.maintab_city_icon, R.drawable.maintab_category_icon};
    int[] imagesHover = new int[]{R.drawable.maintab_bookstand_icon_hover, R.drawable.maintab_stack_icon_press
            , R.drawable.maintab_city_icon_hover, R.drawable.maintab_category_icon_hover};
    String[] texts = new String[]{"书架", "精选", "书库", "发现"};

    /**
     * 初始化tablayout
     */
    private void initTabLayout() {
        tab_layout.setTabMode(MODE_FIXED);
        for (int i = 0; i < 4; i++) {
            View view = getLayoutInflater().inflate(R.layout.tab_item, null);
            ImageView icon = (ImageView) view.findViewById(R.id.icon);
            TextView text = (TextView) view.findViewById(R.id.text);
            if (i == 0) {
                icon.setImageResource(imagesHover[i]);
                text.setText(texts[i]);
                text.setTextColor(getResources().getColor(R.color.main_tab_text_hover));
            } else {
                icon.setImageResource(images[i]);
                text.setText(texts[i]);
                text.setTextColor(getResources().getColor(R.color.main_tab_text));
            }
            view.setTag(i);
            TabLayout.Tab tab = tab_layout.newTab().setCustomView(view).setTag(i);
            Log.i(TAG, "initTabLayout: tab" + i + tab);
            tab_layout.addTab(tab);
        }

        tab_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Log.i(TAG, "onTabSelected: " + tab);
                View customView = tab.getCustomView();
                int tag = (int) customView.getTag();
                ImageView icon = (ImageView) customView.findViewById(R.id.icon);
                TextView text = (TextView) customView.findViewById(R.id.text);

                icon.setImageResource(imagesHover[tag]);
                text.setText(texts[tag]);
                text.setTextColor(getResources().getColor(R.color.main_tab_text_hover));

                if (tag != viewpager.getCurrentItem()) {
                    viewpager.setCurrentItem(tag);
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                Log.i(TAG, "onTabUnselected: " + tab);
                View customView = tab.getCustomView();
                int tag = (int) customView.getTag();
                ImageView icon = (ImageView) customView.findViewById(R.id.icon);
                TextView text = (TextView) customView.findViewById(R.id.text);

                icon.setImageResource(images[tag]);
                text.setText(texts[tag]);
                text.setTextColor(getResources().getColor(R.color.main_tab_text));
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                Log.i(TAG, "onTabReselected: " + tab);
            }
        });
    }


    private void initToolBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setPadding(0, statusBarHeight1, 0, 0);
        toolbar.setBackgroundColor(getResources().getColor(R.color.toolbarColorLucency));
        toolbar.setPopupTheme(R.style.AppTheme);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("");
        invalidateOptionsMenu();
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.hm_search_book:
                        Toast.makeText(MainActivity.this, "搜索", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.action_settings:
                        Toast.makeText(MainActivity.this, "搜索", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.action_settings1:
                        Toast.makeText(MainActivity.this, "搜索", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.action_settings2:
                        Toast.makeText(MainActivity.this, "搜索", Toast.LENGTH_SHORT).show();
                        break;
                }
                return false;
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        // change overflow menu text's color
        try {
            for (int i = 0; i < menu.size(); i++) {
                MenuItem mi = menu.getItem(i);
                String title = mi.getTitle().toString();
                Spannable spannable = new SpannableString(title);
                spannable.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.main_overflow_text_color)), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                mi.setTitle(spannable);
            }
        } catch (Exception ex) {

        }
        return true;
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menu != null) {
            if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
                try {
                    Method m = menu.getClass().getDeclaredMethod(
                            "setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (NoSuchMethodException e) {
//                    Log.e(TAG, "onMenuOpened", e);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }


    public int getToolbarHeight() {
        return toolbar.getHeight();
    }

    public void changeToolbarBg() {
        toolbar.setBackgroundColor(getResources().getColor(R.color.toolbarColor));
    }

    public void resetToolbarBg() {
        toolbar.setBackgroundColor(getResources().getColor(R.color.toolbarColorLucency));
    }


    public void showNotice(String msg) {

        DialogSet.getBookShelfSnackbar(fl_content, msg, GoodSnackbar.LENGTH_SHORT).show();
    }

    /**
     * 隐藏右侧的menu菜单
     */
    public void hideMenu() {
        toolbar.getMenu().setGroupVisible(R.id.group, false);
        // toolbar移除一组menu
//        toolbar.getMenu().removeGroup(R.id.group);
        //隐藏一个menu
//        toolbar.getMenu().findItem(R.id.action_settings).setVisible(false);
    }

    public void showMenu() {
        // toolbar显示组menu
        toolbar.getMenu().setGroupVisible(R.id.group, true);
    }
}
